package util

import (
	"github.com/spf13/afero"
	"github.com/stretchr/testify/assert"
	"testing"
	"time"
)

func startStopCertificatePKIReloader(t *testing.T, r *CertificatePKIReloader) error {
	err := r.Start()
	if err != nil {
		return err
	}
	assert.NoError(t, err, "certificate PKI reloader started successful")
	stopCH := r.stopCh
	r.Stop()

	select {
	case _ = <-stopCH:
		assert.False(t, r.IsRunning(), "certificate PKI reloader stopped successful")
		return nil
	}

}

func TestReloadCerts(t *testing.T) {
	var certPKIRelFullNill *CertificatePKIReloader
	fs := afero.NewOsFs()

	certs, err := GenerateTestCertificates()
	assert.NoError(t, err, "create certificates")

	certPKIRelFull := NewCertificatePKIReloaderFull(fs, certs.certFileName, certs.keyFileName, time.Duration(100))

	assert.NoError(t, startStopCertificatePKIReloader(t, certPKIRelFull), "certificate PKI reloader full start/stop successfully")

	certPKIRel := NewCertificatePKIReloader(certs.certFileName, certs.keyFileName, time.Duration(100))

	assert.NoError(t, startStopCertificatePKIReloader(t, certPKIRel), "certificate PKI reloader  start/stop successfully")

	certPKIRelWithErrHandler := NewCertificatePKIReloaderWithErrHandler(certs.certFileName, certs.keyFileName, time.Duration(100), func(err error) {
		assert.NoError(t, err, "certificate PKI reloader error handler function")
	})

	assert.NoError(t, startStopCertificatePKIReloader(t, certPKIRelWithErrHandler), "certificate PKI reloader with error handler function  start/stop successfully")

	certPKIRelFullWithErrHandler := NewCertificatePKIReloaderFullWithErrHandler(fs, certs.certFileName, certs.keyFileName, time.Duration(100), func(err error) {
		assert.NoError(t, err, "certificate PKI reloader full error handler function")
	})

	assert.NoError(t, startStopCertificatePKIReloader(t, certPKIRelFullWithErrHandler), "certificate PKI reloader full with error handler function start/stop successfully")

	assert.Panics(t, func() {
		_, _ = certPKIRelFullNill.GetCertificate()
	}, "uninit certificate PKI get certificate with panic")

	_, errC := readCert(fs, "/bad_cert_filepath", "/bad_key_filepath")
	assert.Error(t, errC, "uninit certificate PKI read certificate failed")

	tm, _ := readModTime(afero.OsFs{}, "/bad_file_path")
	assert.Zero(t, tm, "uninit certificate PKI read mod time failed")

	assert.Panics(t, func() {
		startStopCertificatePKIReloader(t, certPKIRelFullNill)
	}, "uninit certificate PKI reloader  start/stop with panic")

}
